`
https://leetcode.cn/problems/minimize-the-maximum-edge-weight-of-graph/
`

/**
 * @param {number} n
 * @param {number[][]} edges
 * @param {number} threshold
 * @return {number}
 */
var minMaxWeight = function (n, edges, threshold) {
  // 存在节点没被连起来，所以存在节点到达不了 0
  if (edges.length < n - 1) {
    return -1
  }

  const g = Array.from({ length: n }, () => [])
  for (const [x, y, w] of edges) {
    g[y].push([x, w])
  }

  const visited = new Array(n).fill(0)

  // 从 0 出发，只走 <= upper 的边，能否到达所有节点
  const check = (upper) => {
    const dfs = (x) => {
      visited[x] = upper
      let count = 1
      for (const [y, w] of g[x]) {
        if (w <= upper && visited[y] !== upper) {
          count += dfs(y)
        }
      }
      return count
    }
    return dfs(0) === n
  }

  const maxW = Math.max(...edges.map((node) => node[2]))
  let left = 0, right = maxW + 1
  while (left + 1 < right) {
    const mid = left + Math.floor((right - left) / 2)
    if (check(mid)) {
      right = mid
    } else {
      left = mid
    }
  }
  return right === maxW + 1 ? -1 : right
};